<?php 
$data = [
  ['id'=>1,'name'=>'Jone','age'=>28,'title'=>'baga','salary'=>2000,'action'],
  ['id'=>2,'name'=>'Alice','age'=>22,'title'=>'girl','salary'=>4000,'action'],
  ['id'=>3,'name'=>'Tom','age'=>26,'title'=>'boy','salary'=>3000,'action'],
  ['id'=>4,'name'=>'Yuki','age'=>23,'title'=>'piracise','salary'=>2500,'action'],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST'){
	$searchkey = isset($_POST['search_button'])?trim(htmlspecialchars($_POST['search_key'])):'';
	$searchData = [];
	foreach ($data as $emp){
		if (stripos($emp['title'], $searchkey) !== false) {
			$searchData[] = $emp;
		}else if ($searchkey == '') {
			$searchData[] = $emp;
		}
	}
	$data = $searchData;
}


if(isset($_POST['sort_button'])){
  switch ($_POST['sort_key']) {
  	case 0:
  		usort($data,'compareById');
  		break;
  	case 1:
  	    usort($data,'compareByName');
  	    break;
  	case 2:
  	    usort($data,'compareByAge');
  	    break; 
  	case 3:
  	    usort($data,'compareBySalary');
  	    break;    
  	default:
  		# code...
  		break;
  }
}

/**
 *对数组中年龄进行比较
 *@param $emp1,emp2 数组中要比较的对象
 *@return 返回比较结果
 */
function compareByAge($emp1,$emp2)
{
	return ($emp1['age'] - $emp2['age']);
}


/**
 *对数组中薪水进行比较
 *@param $emp1,emp2 数组中要比较的对象
 *@return 返回比较结果
 */
function compareBySalary($emp1,$emp2)
{
	return ($emp1['salary'] - $emp2['salary']);
}

/**
 *对数组中薪水进行比较
 *@param $emp1,emp2 数组中要比较的对象
 *@return 返回比较结果
 */
function compareById($emp1,$emp2)
{
	return ($emp1['id'] - $emp2['id']);
}

/**
 *对数组中name进行比较
 *@param $emp1,emp2 数组中要比较的对象
 *@return 返回比较结果
 */
function compareByName($emp1,$emp2)
{
	return strcmp($emp1['name'], $emp2['name']);
}

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <style type="text/css">
  	body{}
  	#table{
  	  width: 600px;
  	  border: 1px solid #999;
  	  margin: 10px 0;
  	  text-align: center;
  	}
  </style>
</head>
<body>
  <form method="post">
  	<input type="text" name="search_key" placeholder="key word">
  	<input type="submit" name="search_button"><br/>
  	<select name="sort_key">
  		<option value="0">按id</option>
  		<option value="1">按name</option>
  		<option value="2">按age</option>
  		<option value="3">按salary</option>
  	</select>
  	<input type="submit" name="sort_button"><br/>
  </form>
  <table id="table">
  	<tr>
  	  <th>id</th>
  	  <th>name</th>
  	  <th>age</th>
  	  <th>title</th>
  	  <th>salary</th>
  	  <th>detail</th>
  	</tr>
  	<?php foreach ($data as $emp): ?>
  	<tr>
  	  <td><?=$emp['id'] ?></td>
  	  <td><?=$emp['name'] ?></td>
  	  <td><?=$emp['age'] ?></td>
  	  <td><?=$emp['title'] ?></td>
  	  <td><?=$emp['salary'] ?></td>
  	  <td><a href="detail.php?id=<?php echo $emp['id']?>&n=<?php echo $emp['name']?>&a=<?php echo $emp['age']?>&t=<?php echo $emp['title']?>&s=<?php echo $emp['salary']?>" target="_blank">detail</a></td>
  	</tr>
  	<?php endforeach; ?>
  </table>
</body>
</html>